
package com.sbtr.business.calibration.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sbtr.open.calibration.dto.CalibrationCountByClassifyDto;
import com.sbtr.open.calibration.dto.CalibrationDetailsDto;
import com.sbtr.open.calibration.dto.CalibrationImgDto;
import com.sbtr.open.calibration.dto.CalibrationSearchByDetailsDto;
import com.sbtr.business.calibration.entity.*;
import com.sbtr.common.PageDto;
import com.sbtr.constant.CalibrationConstant;
import com.sbtr.constant.ColumnConstant;
import com.sbtr.util.BeanCopyUtils;
import com.sbtr.util.PageDtoUtils;
import com.sbtr.business.calibration.mapper.CalibrationImgMapper;
import com.sbtr.business.calibration.service.ICalibrationImgService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.*;


/**
 * <p>
 * 标定集 服务实现类
 * </p>
 *

 */
@Transactional
@Service
public class CalibrationImgServiceImpl extends ServiceImpl<CalibrationImgMapper, CalibrationImg>
		implements ICalibrationImgService {

	private static final Logger logger = LoggerFactory.getLogger(CalibrationImgServiceImpl.class);

    @Value("${oss.config.httpPath}")
    private String httpPath;

    @Autowired
    private CalibrationServiceImpl calibrationService;

    @Autowired
    private CalibrationDetailsServiceImpl calibrationDetailsService;

    @Autowired
    private CalibrationRecordDailyServiceImpl calibrationRecordDailyService;

    /**
     * 批量保存标注素材图片信息
     * @param dtos
     * @return
     */
    @Override
    public boolean batchSave(List<CalibrationImgDto> dtos){
        List<CalibrationImg> CalibrationImgs = BeanCopyUtils.copyProperties(dtos, CalibrationImg.class);
        return saveBatch(CalibrationImgs);
    }

    @Override
    public PageDto<CalibrationImgDto> getImgCalibrate(CalibrationSearchByDetailsDto dto){
        IPage<CalibrationImg> page = new Page<>();
        page.setSize(dto.getPageSize());
        page.setCurrent(dto.getPage());
        QueryWrapper<CalibrationImg> wrapper = new QueryWrapper<>();

        if (null != dto.getId()) {
            wrapper.eq("calibration_id", dto.getId());
        }
        if (StringUtils.isNotEmpty(dto.getFinisher())) {
            wrapper.eq("finisher", dto.getFinisher());
        }
        if(null !=dto.getCalibrationDetailId()){
            wrapper.eq("calibration_detail_id",dto.getCalibrationDetailId());
        }
        if (StringUtils.isNotEmpty(dto.getCompleted())) {
            wrapper.eq("completed", dto.getCompleted());
        }
        if (null != dto.getClassifyId()) {
            wrapper.eq("classify_id", dto.getClassifyId());
        }

//		wrapper.orderByDesc("id");
        page = page(page, wrapper);
        PageDto<CalibrationImgDto> pageDto = PageDtoUtils.getPageDtoByIPage(page, CalibrationImgDto.class);
        List<CalibrationImgDto> CalibrationImgDtoList = pageDto.getList();
        for (CalibrationImgDto calibrationImgDto: CalibrationImgDtoList){
            calibrationImgDto.setRelativePath(httpPath+calibrationImgDto.getRelativePath());
            calibrationImgDto.setThumbnailRelativePath(httpPath+calibrationImgDto.getThumbnailRelativePath());
        }
        pageDto.setList(CalibrationImgDtoList);
        return pageDto;
    }

    @Override
    public CalibrationImgDto findById(Long id){
        return BeanCopyUtils.copyProperties(getById(id), CalibrationImgDto.class);
    }

    @Override
    public List<CalibrationCountByClassifyDto> countImgHasCalibrated(Long calibrationDetailsId)
    {
        CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
        String finisher=calibrationDetailsDto.getFinisher();
        Long calibration_id=calibrationDetailsDto.getCalibrationId();

        List<CalibrationCountByClassifyDto>dtoList=baseMapper.countImgHasCalibrated(finisher,calibration_id);
        return dtoList;
    }

    @Override
    public List<CalibrationImgDto> saveImgCalibrate(Long calibrationDetailsId,
                                                    List<CalibrationImgDto> dtos){
        List<CalibrationImg> calibrationImgs = BeanCopyUtils.copyProperties(dtos, CalibrationImg.class);

        for (CalibrationImg detail : calibrationImgs) {
//            detail.setCalibrationId(calibrationId);
            if (null != detail.getClassifyId()) {
                detail.setCompleted("1"); // 已标注
            } else {
                detail.setCompleted("0"); // 未标注
            }
        }
        boolean tag = saveOrUpdateBatch(calibrationImgs);

        if (tag) {
            // 更新发布任务的数据统计
            CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
            updateCalibrationImgCount(calibrationDetailsDto.getCalibrationId());
            //更新个人接受任务的数据统计
//            CalibrationDto calibrationDto=calibrationService.findById(calibrationId);
            updateCalibrationDetailsImgCount(calibrationDetailsDto);
            //更新每日标注统计
            updateCalibrationImgRecordDaily(calibrationDetailsDto);
        }

        return BeanCopyUtils.copyProperties(calibrationImgs, CalibrationImgDto.class);
    }

    @Override
    public List<CalibrationImgDto> saveImgSkip(Long calibrationDetailsId,
                                        List<CalibrationImgDto> dtos){
        List<CalibrationImg> calibrationImgs = BeanCopyUtils.copyProperties(dtos, CalibrationImg.class);

        for (CalibrationImg detail : calibrationImgs) {
//            detail.setCalibrationId(calibrationId);
            detail.setCompleted("2");
        }
        boolean tag = saveOrUpdateBatch(calibrationImgs);

        if (tag) {
            // 更新发布任务的数据统计
            CalibrationDetailsDto calibrationDetailsDto = calibrationDetailsService.findById(calibrationDetailsId);
            updateCalibrationImgCount(calibrationDetailsDto.getCalibrationId());
            //更新个人接受任务的数据统计
//            CalibrationDto calibrationDto=calibrationService.findById(calibrationId);
            updateCalibrationDetailsImgCount(calibrationDetailsDto);
        }

        return BeanCopyUtils.copyProperties(calibrationImgs, CalibrationImgDto.class);
    }

    // 更新图片类型的发布任务的数据统计
    @Override
    public boolean updateCalibrationImgCount(Long calibrationId) {
//        QueryWrapper<Calibration> wrapper = new QueryWrapper<>();
//        wrapper.eq("id", calibrationIds);
//        List<Calibration> list = calibrationService.list(wrapper);
        Calibration calibration = calibrationService.getById(calibrationId);
        if (null != calibration){
            QueryWrapper<CalibrationImg> wrapper = new QueryWrapper<>();
            wrapper.eq("calibration_id", calibrationId);
            Integer totalCount = count(wrapper);
            wrapper.eq("completed", "1");
            Integer completeCount = count(wrapper);

            calibration.setTotalCount(totalCount);
            calibration.setCompleted(completeCount);
            if(completeCount.equals(totalCount)){
                calibration.setStatus(CalibrationConstant.TASK_STATUS_COMPLETED); // 已完成
            }

            return calibrationService.updateById(calibration);
        }
        return false;
    }

    // 更新图片类型的个人接受任务的数据统计
    @Override
    public boolean updateCalibrationDetailsImgCount(CalibrationDetailsDto calibrationDetailsDto) {

        QueryWrapper<CalibrationImg> wrapper = new QueryWrapper<>();
        Long calibrationIds = calibrationDetailsDto.getCalibrationId();
        String finisher = calibrationDetailsDto.getFinisher();
        wrapper.eq("calibration_id", calibrationIds);
        wrapper.eq("finisher",finisher);
        Integer totalCount = count(wrapper);
        wrapper.eq("completed", "1");
        Integer completeCount = count(wrapper);

        CalibrationDetails calibrationDetails = BeanCopyUtils.copyProperties(calibrationDetailsDto, CalibrationDetails.class);
        calibrationDetails.setTotalCount(totalCount);
        calibrationDetails.setCompleted(completeCount);
        if(completeCount.equals(totalCount)){
            calibrationDetails.setStatus(CalibrationConstant.TASK_STATUS_COMPLETED); // 已完成
        }

        return calibrationDetailsService.updateById(calibrationDetails);
    }

    //更新每日标注统计
    @Override
    public boolean updateCalibrationImgRecordDaily(CalibrationDetailsDto calibrationDetails){
        QueryWrapper<CalibrationImg> wrapper = new QueryWrapper<>();
        long calibrationId = calibrationDetails.getCalibrationId();
        String finisher = calibrationDetails.getFinisher();
        wrapper.eq("calibration_id", calibrationId);
        wrapper.eq("finisher",finisher);
//		Integer totalCount = count(wrapper);
        wrapper.eq("completed", "1");
        Calendar calendar = new GregorianCalendar();
        //        Calendar calendar = Calendar.getInstance();//日历对象
        calendar.setTime(new Date());//当天时间赋给日历对象
        calendar.set(Calendar.HOUR_OF_DAY, 0);//设置对象日历格式
        calendar.set(Calendar.MINUTE, 0);//设置为当天零点
        calendar.set(Calendar.SECOND, 0);
        Date updateTimeFrom = calendar.getTime();//再返回时间对象
        calendar.add(Calendar.DAY_OF_MONTH, 1);//把日期往后增加一天,整数  往后推,负数往前移动
        Date updateTimeTo = calendar.getTime();//返回另一个时间对象
        wrapper.between(ColumnConstant.UPDATE_TIME, updateTimeFrom, updateTimeTo);
        Integer completeCount = count(wrapper);
        CalibrationRecordDaily calibrationRecordDaily = calibrationRecordDailyService.findByCalibrationIdFinisher(calibrationId, finisher);
        if(null == calibrationRecordDaily){
            calibrationRecordDaily = new CalibrationRecordDaily();
            calibrationRecordDaily.setCalibrationId(calibrationId);
            calibrationRecordDaily.setFinisher(finisher);
            calibrationRecordDaily.setCalibrationDetailId(calibrationDetails.getId());
            calibrationRecordDaily.setUpdateTime(new Date());
            calibrationRecordDaily.setCompletedCount(completeCount);
        }else {
            calibrationRecordDaily.setUpdateTime(new Date());
            calibrationRecordDaily.setCompletedCount(completeCount);
        }
        return calibrationRecordDailyService.saveOrUpdate(calibrationRecordDaily);
    }

    @Override
    public List<CalibrationImgDto> findCompletedByCalibrationId(Long calibrationId){
        QueryWrapper<CalibrationImg> wrapper = new QueryWrapper<>();
        wrapper.eq("calibration_id", calibrationId);
        wrapper.eq("completed", "1");
        List<CalibrationImg> calibrationImgList = list(wrapper);
        return BeanCopyUtils.copyProperties(calibrationImgList, CalibrationImgDto.class);
    }

    @Override
    public List<CalibrationImgDto> findCompletedByFinisher(Long calibrationId,String finisher){
        QueryWrapper<CalibrationImg> wrapper = new QueryWrapper<>();
        wrapper.eq("calibration_id", calibrationId);
        wrapper.eq("finisher", finisher);
        wrapper.eq("completed", "1");
        List<CalibrationImg> calibrationImgList = list(wrapper);
        return BeanCopyUtils.copyProperties(calibrationImgList, CalibrationImgDto.class);
    }

}